#!/bin/bash

PGNAME=`basename $0`
PGDIRNAME=`dirname $0`
PGERR="$PGNAME[$$]: "

if [ "${MLPROD_HOME}" == "" ]
then
  echo "${PGERR} :  MLPROD_HOME env not set;  exiting !!!" >&2
  exit 1
fi
PGCFG_FILE="${MLPROD_HOME}/config/mlenv.rc"
PGLOG="${MLPROD_HOME}/log/dblog.log"

if [ ! -f ${PGCFG_FILE} ]
then
  echo "${PGERR} : config file <${PGCFG_FILE}> found; exiting !!!" >&2
  exit 2
fi
. ${PGCFG_FILE}

cd "${PGDIRNAME}"
if [ $? -ne 0 ]
then
  echo "${PGERR} : unable to change to dir ${PGDIRNAME}; exiting !!!" >&2
  exit 2
fi


function usage
(
  echo "Usage: ${PGNAME} [-v]" >&2
)

if [ $# -gt 1 ] || [ $# -eq 1 ] && [ "$1" != "-v" ]
then
  usage;
  exit 3
fi
VERBOSE="$1"
PGSQL="${MLBIN_DIR}/pgsql ${VERBOSE} -f "

# setup demographics database
SQL_FILES="\
 create_funcs_audit.sql \
 create_funcs_batch_temp_insurance2.sql \
 create_funcs_batch_insurance2.sql \
 create_funcs_insurance2_results.sql \
 create_funcs_insurance2_output_recon.sql \
"


TEST_SQL_FILES="\
"


for sqlf in $SQL_FILES
do
  ${PGSQL} $sqlf
  if [ $? -ne 0 ]
  then
    echo "${PGERR}: failed while processing sql file : $sqlf" >&2
    exit 4;
  fi
done

for sqlf in $TEST_SQL_FILES
do
  ${PGSQL} $sqlf
  if [ $? -ne 0 ]
  then
    echo "${PGERR}: failed while running test sql file : $sqlf" >&2
    exit 5;
  fi
done
